/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Game;
import model.GameManager;
import model.Player;
import model.PlayerDao;

import com.sampullara.poker.Card;

/**
 *
 * @author Gebruiker
 */
public class TableController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private GameManager gameManager;

    public TableController(){
        super();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        HttpSession thisSession = request.getSession();
        assert(thisSession != null);
        String gameID = (String) thisSession.getAttribute("game");
        Game game = gameManager.getGame(gameID);
        if(gameManager.getGame(gameID) == null) {}
        
        //Controleren of speler aan de beurt is, en actie doorgeven aan model.
        else if(request.getParameter("turn") != null) {
            if(game.isStarted()){
                if(thisSession.getId().equals(game.getActivePlayer().getSession())) {
                    Player player = game.getActivePlayer();
                    if(request.getParameter("action") != null){
                        String action = request.getParameter("action");
                        if(action.equals("check")){
                            game.check();
                        } else if(action.equals("bet")) {
                        	try {
                        		int amount = Integer.parseInt(request.getParameter("amount"));
                        		game.bet(player, amount);
                        	} catch(Exception e) {
                        	}
                        } else if(action.equals("fold")){
                            game.fold(player);
                        } else if(action.equals("call")){
                            game.call(player);
                        }
                    }
                }
            }
        }
        StringBuffer returnXML = null;
        if(gameManager.getGame(gameID) == null) {}
        //Nagaan of speler die GET aanroept aan de beurt is.
        else {
	        String responseText;
	        if(game.isStarted()) {
	            synchronized (game.getActivePlayer()) {
	                responseText = (game.getActivePlayer().getSession().equals(thisSession.getId())? "true" : "false");
	            }
	        } else {
	            responseText = "false";
	        }
	        //Als status NIET waiting is, en het spel dus begonnen is.
	        if(!(game.getState().equals("waiting"))) {
		        
	        	//Indien de GET 'de parameter 'update' bevat, benodigde gegevens uitrekenen met behulp van model.
		        if(request.getParameter("update") != null) {
		        	String card1 = "";
		        	String card2 = "";
		        	String bc1 = "";
		        	String bc2 = "";
		        	String bc3 = "";
		        	String bc4 = "";
		        	String bc5 = "";
		        	ArrayList<Player> players = game.getPlayers();
		        	Player player1 = null;
		        	Player player2 = null;
		        	Player player3 = null;
		        	Player player4 = null;
		        	String activePlayer = "";
		        	for(Player p : players) {
		        		if(p == game.getActivePlayer()) {
	        				activePlayer = p.getName();
	        			}
		        		if(p.getSession().equals(thisSession.getId())) {
		        			//Spelers op volgorde zetten, zodat iedere browser de eigen speler onderaan heeft.
		        			player1 = p;
		        			int index = players.indexOf(p);
		        			if(index == 0) {
		        				player2 = players.get(1);
		        				player3 = players.get(2);
		        				player4 = players.get(3);
		        			}
		        			if(index == 1) {
		        				player2 = players.get(2);
		        				player3 = players.get(3);
		        				player4 = players.get(0);
		        			}
		        			if(index == 2) {
		        				player2 = players.get(3);
		        				player3 = players.get(0);
		        				player4 = players.get(1);
		        			}
		        			if(index == 3) {
		        				player2 = players.get(0);
		        				player3 = players.get(1);
		        				player4 = players.get(2);
		        			}
		        			//Kaarten van speler ophalen.
		        			try {
			        			card1 = "images/" + getImagePath(p.getCards().get(0));
			        			card2 = "images/" + getImagePath(p.getCards().get(1));
		        			} catch(Exception e) { }
		        		}
		        	}
		        	
		        	List<Card> bc = game.getBoard().getCards();
		        	//XML opbouwen om naar view te sturen.
		    		returnXML = new StringBuffer("\r\n<game>");
		    		
		    		returnXML.append("\r\n<players>");
		    			returnXML.append("\r\n<player>");
			    			returnXML.append("\r\n<name>" + player1.getName() + "</name>");
			    			returnXML.append("\r\n<balance>" + new PlayerDao().getChips(player1.getName()) + "</balance>");
			    			returnXML.append("\r\n<bet>" + player1.getCurrentBet() + "</bet>");
			    			returnXML.append("\r\n<folded>" + player1.getFolded() + "</folded>");
			    		returnXML.append("\r\n</player>");
			    		returnXML.append("\r\n<player>");
			    			returnXML.append("\r\n<name>" + player2.getName() + "</name>");
			    			returnXML.append("\r\n<balance>" + new PlayerDao().getChips(player2.getName()) + "</balance>");
			    			returnXML.append("\r\n<bet>" + player2.getCurrentBet() + "</bet>");
			    			returnXML.append("\r\n<folded>" + player2.getFolded() + "</folded>");
			    		returnXML.append("\r\n</player>");
				    	returnXML.append("\r\n<player>");
							returnXML.append("\r\n<name>" + player3.getName() + "</name>");
							returnXML.append("\r\n<balance>" + new PlayerDao().getChips(player3.getName()) + "</balance>");
							returnXML.append("\r\n<bet>" + player3.getCurrentBet() + "</bet>");
							returnXML.append("\r\n<folded>" + player3.getFolded() + "</folded>");
						returnXML.append("\r\n</player>");
						returnXML.append("\r\n<player>");
							returnXML.append("\r\n<name>" + player4.getName() + "</name>");
							returnXML.append("\r\n<balance>" + new PlayerDao().getChips(player4.getName()) + "</balance>");
							returnXML.append("\r\n<bet>" + player4.getCurrentBet() + "</bet>");
							returnXML.append("\r\n<folded>" + player4.getFolded() + "</folded>");
						returnXML.append("\r\n</player>");
			    		returnXML.append("\r\n</players>");
		
		    		returnXML.append("\r\n<turn>");
		                    returnXML.append("\r\n<currentplayer>" + activePlayer + "</currentplayer>");
		                    returnXML.append("\r\n<turncheck>" + responseText + "</turncheck>");
		    		returnXML.append("\r\n</turn>");
		
		    		returnXML.append("\r\n<hand>");
		    			returnXML.append("\r\n<card>" + card1 + "</card>");
		    			returnXML.append("\r\n<card>" + card2 + "</card>");
		    		returnXML.append("\r\n</hand>");
		
		    		returnXML.append("\r\n<board>");
		    			returnXML.append("\r\n<state>" + game.getState() + "</state>");
		    			returnXML.append("\r\n<pot>" + game.getPot() + "</pot>");
		    			returnXML.append("\r\n<highestBet>" + game.getHighestBet() + "</highestBet>");
		    			returnXML.append("\r\n<dealer>" + game.getActivePlayers().get(1).getName() + "</dealer>");
		    			//Als er nog geen kaarten open liggen, plaatjes van kaarten resetten.
		    			if(!(game.getState().equals("waiting") || game.getState().equals("started") || game.getState().equals("preflop"))) {
			    			returnXML.append("\r\n<cards>");
			    			if(game.getState().equals("preflop")) {
			    			}
			    			if(game.getState().equals("flop")) {
			    				bc1 = "images/" + getImagePath(bc.get(0));
			    				bc2 = "images/" + getImagePath(bc.get(1));
			    				bc3 = "images/" + getImagePath(bc.get(2));
			    				returnXML.append("\r\n<card>" + bc1 + "</card>");
			    				returnXML.append("\r\n<card>" + bc2 + "</card>");
			    				returnXML.append("\r\n<card>" + bc3 + "</card>");
			            	}
			    			if(game.getState().equals("turn")) {
			    				bc1 = "images/" + getImagePath(bc.get(0));
			    				bc2 = "images/" + getImagePath(bc.get(1));
			    				bc3 = "images/" + getImagePath(bc.get(2));
			    				bc4 = "images/" + getImagePath(bc.get(3));
			    				returnXML.append("\r\n<card>" + bc1 + "</card>");
			    				returnXML.append("\r\n<card>" + bc2 + "</card>");
			    				returnXML.append("\r\n<card>" + bc3 + "</card>");
			    				returnXML.append("\r\n<card>" + bc4 + "</card>");
			            	}
			    			if(game.getState().equals("river")) {
			    				bc1 = "images/" + getImagePath(bc.get(0));
			    				bc2 = "images/" + getImagePath(bc.get(1));
			    				bc3 = "images/" + getImagePath(bc.get(2));
			    				bc4 = "images/" + getImagePath(bc.get(3));
			    				bc5 = "images/" + getImagePath(bc.get(4));
			    				returnXML.append("\r\n<card>" + bc1 + "</card>");
			    				returnXML.append("\r\n<card>" + bc2 + "</card>");
			    				returnXML.append("\r\n<card>" + bc3 + "</card>");
			    				returnXML.append("\r\n<card>" + bc4 + "</card>");
			    				returnXML.append("\r\n<card>" + bc5 + "</card>");
			            	}
			    			returnXML.append("\r\n</cards>");
		        }
		    		returnXML.append("\r\n</board>");
		
		    		returnXML.append("\r\n</game>");
		
		    		response.setHeader("Cache-Control", "no-cache");
		        }
		        response.setContentType("text/xml");
	        }

	        if(returnXML != null) {
	        	response.getWriter().write(returnXML.toString());
	        }
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    }

    public void init(){
    	gameManager = (GameManager)getServletContext().getAttribute("gameManager");
    }

    //Het pad van benodigde plaatje nagaan.
	public String getImagePath(Card card) {
		String path = "";
		switch (card.getSuit()) {
		case CLUBS:
			path = "card-" + card.getRank() + "-" + "0.gif";
			break;
		case DIAMONDS:
			path = "card-" + card.getRank() + "-" + "1.gif";
			break;
		case HEARTS:
			path = "card-" + card.getRank() + "-" + "2.gif";
			break;
		case SPADES:
			path = "card-" + card.getRank() + "-" + "3.gif";
			break;
		default:
			path = "back_blue_casino.gif";
		}
		return path;
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
